package ait642.towson.edu.client;

/**
 * \
 * 
 * @author Tariku Tessema Assignment 2 Modifying Legacy Code
 */
public class Stutter {

	/**
	 * The main method.
	 * 
	 * @param args
	 *            the Textarea content
	 */
	private static String allStutteredWords = "";

	public Stutter(String textAreaContent) {
		String stutterCheck;
		boolean hasStutter = false;
		Integer lineNumber;
		lineNumber = 1;
		int lineCounter;

		// Add line break for one line text
		if (textAreaContent.indexOf("\n") == 0) {
			textAreaContent += "\n";
		}

		try {
			for (lineCounter = 0; lineCounter < textAreaContent.split("\n").length; lineCounter++) {
				stutterCheck = getStutteredWord(
						textAreaContent.split("\n")[lineCounter], lineNumber);
				if (stutterCheck != "") {
					hasStutter = true;
					allStutteredWords += printStutteredWord(stutterCheck,
							lineNumber);
				}
				lineNumber++;
			}
			if (hasStutter == false) {
				allStutteredWords = "";
			}

		} catch (Exception e) {
			// Handle file exceptions
			e.printStackTrace();
		}
	}

	/**
	 * Gets the suttured words.
	 * 
	 * @return the suttured words
	 */
	public String getSutturedWords() {
		if (allStutteredWords != "") {
			return "<b>Repeated Words</b><br />" + allStutteredWords;
		} else {
			return "No repeated words found.";
		}
	}

	/**
	 * Gets the stuttered word.
	 * 
	 * @param newLine
	 *            the new line
	 * @param lineNumber
	 *            the line number
	 * @return the stuttered word
	 */
	private static String getStutteredWord(String newLine, Integer lineNumber) {
		String word = "";
		int i = 0;

		for (i = 0; i < newLine.split(" ").length; i++) {
			// Check the word before current selected word
			if (i > 0) {
				if (newLine.split(" ")[i - 1].toString().equalsIgnoreCase(
						newLine.split(" ")[i].toString())) {
					word = newLine.split(" ")[i].toString();
				}
				// Check the word after current selected word
				if (i < newLine.split(" ").length - 1) {
					if (newLine.split(" ")[i + 1].toString().equalsIgnoreCase(
							newLine.split(" ")[i].toString())) {
						word = newLine.split(" ")[i].toString();
					}
				}
			}
		}
		return word;
	}

	/**
	 * Gets the stuttered word with line number.
	 * 
	 * @param word
	 *            the word
	 * @param lineNumber
	 *            the line number
	 */
	private static String printStutteredWord(String word, Integer lineNumber) {
		String strRtn;
		strRtn = "";

		strRtn += "Line Number :" + String.valueOf(lineNumber)
				+ " ------------- " + word + "<br />";
		return strRtn;
	}
}
